<template>
  <div class="bg">
  <div class="container">
    <div style="font-size: 20px; font-weight: bold;text-align: center ;color: rgb(95, 100, 102);line-height: 80px;">用户注册</div>
    <div style="align-items: center;padding-left: 20px;padding-right: 40px;">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm" >
        <el-form-item label="用户名" prop="user_name">
            <el-input  v-model="ruleForm.user_name" placeholder="请输入用户名" />
        </el-form-item>
        <!-- <el-form-item label="身   份" prop="role">
          <el-select v-model="ruleForm.role" placeholder="请选择你要注册的身份">
            <el-option label="普通员工" value="1" />
            <el-option label="管理员" value="2" />
            <el-option label="超级管理员" value="3" />
          </el-select>    
        </el-form-item> -->
        <el-form-item label="密   码" prop="password">
            <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码"  show-password autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
            <el-input style="margin-top: 10px;"  v-model="ruleForm.checkPass"  type="password"  placeholder="请确认密码"  show-password autocomplete="off"/>
        </el-form-item>
      <el-form-item v-if="ruleForm.password !== '' && ruleForm.password !== undefined" label="" align="center"  style="height: 25px">
        <!-- 展示长度条 -->
        <div class="bar" v-if="ruleForm.password !== '' && ruleForm.password !== undefined" :style="{ background: barColor, width: width + '%' }">
        <!-- 展示文字 -->
          <div class="strength"  :style="{ color: barColor }" v-if="ruleForm.password !== '' && ruleForm.password !== undefined">{{ strength }}</div>
        </div>
      </el-form-item>
    </el-form>
    <div style="padding: 0 80px;" > 
        <div style="float: left;" ><el-button type="primary" @click="Register(ruleFormRef)">注 册</el-button></div>
        <div style="float: right;" ><el-button @click="reset(ruleFormRef)">重 置</el-button></div>
    </div>
    <div style="margin-top: 75px; padding: 0 30px;">已有账号，请 <a style="color: #1a2ee6;text-decoration: none;" href="http://localhost:3000/login">登录</a></div>        
  </div>
	</div>
</div>
</template>

<script lang="ts" setup>
import { reactive, ref ,watch} from 'vue'
import type { FormInstance, FormRules  } from 'element-plus'
import {ElMessage}from 'element-plus'
import { registerApi } from '../utils/api/login'
// 引入验证方法
import {  level ,checkPasswordRule} from '../stores/CheckPassword'
//路由
import {useRouter} from 'vue-router'

const router = useRouter();
const ruleFormRef = ref<FormInstance>()
// 强度条颜色
const barColor = ref('');
// 强度条长度
const width = ref('');
// 强度条说明
const strength = ref('');
const ruleForm = reactive({
  password: '',
  checkPass: '',
  user_name: '',
  // role: '',
  
})

const checkUserName = (rule: any, value: any, callback: any) => {
        if (value.trim() === '') {
            callback(new Error("用户名不可为空"))
        } else {
            return callback();
        }}

const validatePass = (rule: any, value: string, callback: any) => {
  if (value.trim() === '') {
       callback(new Error("请输入密码"))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass')
    }
    const result: string = checkPasswordRule(value,ruleForm.user_name);
      if (result === '校验通过') {
        callback();
      } else {
        callback(new Error(result));
      }
  }
}
const comValidatePass = (rule: any, value: any, callback: any) => {
  if (value.trim() === '') {
      callback(new Error("请确认密码"))
  } else if (value !== ruleForm.password) {
    callback(new Error("两次密码输入不匹配"))
  } else {
    callback()
  }
}

watch(() => ruleForm.password,
    (newVal) => {
      if (newVal != '') {
        const res: string = level(newVal);
        if (res == '非常弱') {
          barColor.value = 'red';
          width.value = '20';
          strength.value = '非常弱';
        } else if (res == '弱') {
          barColor.value = '#ee795c';
          width.value = '40';
          strength.value = '弱';
        } else if (res == '一般') {
          barColor.value = 'orange';
          width.value = '60';
          strength.value = '一般';
        } else if (res == '强') {
          barColor.value = 'green';
          width.value = '80';
          strength.value = '强';
        } else if (res == '非常强') {
          barColor.value = '#1B8EF8';
          width.value = '100';
          strength.value = '非常强';
        }
      }
    }
  )
const rules = reactive<FormRules<typeof ruleForm>>({
  user_name: [{required: true, message: '请输入3-20位用户名', trigger: 'blur'},
            {
                min: 3,
                max: 20,
                message: '请输入3-20位用户名',
                trigger: 'blur'
            },
            {
                validator: checkUserName,
                trigger: 'blur'}
              ],
  password: [{required: true, message: '请输入8-16位密码', trigger: 'blur'},
            {
                min: 8,
                max: 16,
                message: '请输入8-16位密码',
                trigger: 'blur'
            },
            {
                validator: validatePass,
                trigger: 'blur'}],
  checkPass: [{ required: true,validator: comValidatePass, trigger: 'blur' }],
  // role: [{required: true,message: '请选择你要注册的身份',trigger: 'blur'}],
})

const Register = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 发送注册请求
      registerApi({
					user_name: ruleForm.user_name, 
					password: ruleForm.password,
          // role:ruleForm.role
				}).then((res:{code:string;message:any})=> {
          if(res.code!="0"){
          ElMessage.error(res.message)
          }else{
            // 注册成功
          ElMessage({
               message: res.message,
               type: 'success',
           })
          router.push('/login')
          }
					
				}).catch(error=>{
          ElMessage.error(error.response.data.message)
        })
      } else {
        ElMessage.error("请输入正确的格式");      
      }
    })
  }
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style scoped>
     .bg{
      margin: 0; 
      padding: 0; 
      width: 100%; 
      height: 100vh; 
      background-image:  url('../assets/img/BG.png'); 
      background-size: cover; 
      background-repeat: no-repeat; 
      background-position: center; 
      }
      .container {
          width: 410px;
          height: 400px;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          background-color: #fdffff;
          border-radius: 10px;

      }
      
      .strength {
        font-size: 13px;
        color: #271E25;
        position: relative;
        top: 5px;
        left: 0;
        transition: 0.5s all ease;
      }  
      .bar {
        /* width: 400px; */
        height: 5px;
        background: red;
        transition: 0.5s all ease;
        max-width: 420px;
        margin: 2px 0 5px 5px;
        position: absolute;

      }
	
</style>